# 21. 合并两个有序链表
// 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function(list1, list2) {
if (!list1 && !list2) return null;
const head = new ListNode();
let p = head;
while (list1 && list2) {
if (list1.val < list2.val) {
p.next = list1;
list1 = list1.next;
} else {
p.next = list2;
list2 = list2.next;
}
p = p.next;
}
if (list1) p.next = list1;
if (list2) p.next = list2;
return head.next;
};
console.log(
JSON.stringify(
mergeTwoLists(
{
val: 1,
next: {
val: 2,
next: {
val: 4,
next: null,
},
},
},
{
val: 1,
next: {
val: 3,
next: {
val: 4,
next: null,
},
},
}
)
)
); // [1,1,2,3,4,4]
console.log(mergeTwoLists(null, null)); // []
console.log(mergeTwoLists(null, { val: 0, next: null })); // [0]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60